import moment from 'moment';

// constants.js
var PALACES = ["命宫", "兄弟宫", "夫妻宫", "子女宫", "财帛宫", "疾厄宫", "迁移宫", "交友宫", "事业宫", "田宅宫", "福德宫", "父母宫"];
var STEMS = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
var BRANCHES = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
var STAR_DESCRIPTIONS = {
    "紫薇": "紫微坐命，主贵气，有领导才能，为人稳重，具决断力。",
    "天机": "天机星聪慧，善谋略，但易多思多虑。",
    "太阳": "太阳星热情大方，光明磊落，有活力。",
    "武曲": "武曲星坚毅果断，有财运，但有时过于刚直。",
    "天同": "天同星温和善良，知足常乐，但可能缺乏进取心。",
    "廉贞": "廉贞星忠诚正直，有原则，但情绪易波动。",
    "天府": "天府星稳重保守，善于理财和管理。",
    "太阴": "太阴星温柔细腻，富有艺术气质。",
    "贪狼": "贪狼星多才多艺，善于交际，但欲望较强。",
    "巨门": "巨门星口才好，善于分析，但有时言辞尖锐。",
    "天相": "天相星忠诚公正，善于协调人际关系。",
    "天梁": "天梁星慈悲为怀，有责任感，但可能过于保守。",
    "七杀": "七杀星勇敢果断，有冲劲，但易冲动。",
    "破军": "破军星富有创新精神，敢于突破，但稳定性稍差。",
};


// lunarConversion.js
function gregorianToLunar(date) {
    var momentDate = moment(date);
    if (!momentDate ||!momentDate.isValid()) {
        return null;
    }
    var lunarDate = momentDate.format('YYYY-MM-DD');
    var year = parseInt(lunarDate.split('-')[0]);
    var month = parseInt(lunarDate.split('-')[1]);
    var day = parseInt(lunarDate.split('-')[2]);
    var yearStemIndex = (year - 3) % 10;
    var yearBranchIndex = (year - 3) % 12;
    var sizhu = [STEMS[yearStemIndex] + BRANCHES[yearBranchIndex], '', '', ''];
    return {
        yinli_num: {
            month: month,
            day: day,
        },
        sizhu: sizhu,
    };
}

function normalizeIndex_back(n) {
    return n > 11? (n -= 12) : n < 0? (n += 12) : n;
}

function getDiZhiByMonthAndDay(lunarData, hour) {
    var n = lunarData.yinli_num.month;
    var dayIndex = "子丑寅卯辰巳午未申酉戌亥".split("").findIndex(function (n) { return n === lunarData.sizhu[3][1]; });
    var o = dayIndex + 1;
    var baseIndex = n - o + 0;
    if (hour >= 23 || hour < 1) {
        baseIndex += 0;
    } else if (hour >= 1 && hour < 3) {
        baseIndex += 1;
    } else if (hour >= 3 && hour < 5) {
        baseIndex += 2;
    } else if (hour >= 5 && hour < 7) {
        baseIndex += 3;
    } else if (hour >= 7 && hour < 9) {
        baseIndex += 4;
    } else if (hour >= 9 && hour < 11) {
        baseIndex += 5;
    } else if (hour >= 11 && hour < 13) {
        baseIndex += 6;
    } else if (hour >= 13 && hour < 15) {
        baseIndex += 7;
    } else if (hour >= 15 && hour < 17) {
        baseIndex += 8;
    } else if (hour >= 17 && hour < 19) {
        baseIndex += 9;
    } else if (hour >= 19 && hour < 21) {
        baseIndex += 10;
    } else if (hour >= 21 && hour < 23) {
        baseIndex += 11;
    }
    return PALACES[normalizeIndex(baseIndex)];
}


// palaceGeneration.js
function generateTwelvePalaces(start, arr, isShunShizheng) {
    var t = {};
    for (var i = 0; i < arr.length; i++) {
        var a = normalizeIndex(isShunShizheng? start + i : start - i);
        t[PALACES[a]] = arr[i];
    }
    return t;
}

function normalizeIndex(n) {
    return n > 11? (n -= 12) : n < 0? (n += 12) : n;
}

// fiveElementsBureau.js
function determineFiveElementsBureau(lunarData) {
    var month = lunarData.yinli_num.month;
    var bureauMap = {
        1: "金四局",
        2: "金四局",
        3: "水二局",
        4: "水二局",
        5: "火六局",
        6: "火六局",
        7: "金四局",
        8: "金四局",
        9: "水二局",
        10: "水二局",
        11: "火六局",
        12: "火六局",
    };
    return bureauMap[month] || "未知五行局";
}


// ziweiPalace.js
function determineZiWeiPalace(day, fiveElementsBureau) {
    var i = "";
    switch (fiveElementsBureau) {
        case "水二局":
            i = "丑寅寅卯卯辰辰巳巳午午未未申申酉酉戌戌亥亥子子丑丑寅寅卯卯辰"[day - 1];
            break;
        case "火六局":
            i = "酉午亥辰丑寅戌未子巳寅卯亥申丑午卯辰子酉寅未辰巳丑戌卯申巳午"[day - 1];
            break;
        case "金四局":
            i = "亥辰丑寅子巳寅卯丑午卯辰寅未辰巳卯申巳午辰酉午未巳戌未申午亥"[day - 1];
            break;
        default:
            i = "未知";
    }
    return i;
}

// starGeneration.js

function generateFourteenStars(n) {
    var o = [];
    var i = "";
    switch (n) {
        case "子":
            i = "亥酉申未辰辰巳午未申酉戌寅";
            break;
        case "丑":
            i = "子戌酉申巳卯辰巳午未申酉丑";
            break;
        case "寅":
            i = "丑亥戌酉午寅卯辰巳午未申子";
            break;
        case "卯":
            i = "寅子亥戌未丑寅卯辰巳午未亥";
            break;
        case "辰":
            i = "卯丑子亥申子丑寅卯辰巳午戌";
            break;
        case "巳":
            i = "辰寅丑子酉亥子丑寅卯辰巳酉";
            break;
        case "午":
            i = "巳卯寅丑戌戌亥子丑寅卯辰申";
            break;
        case "未":
            i = "午辰卯寅亥酉戌亥子丑寅卯未";
            break;
        case "申":
            i = "未巳辰卯子申酉戌亥子丑寅午";
            break;
        case "酉":
            i = "申午巳辰丑未申酉戌亥子丑巳";
            break;
        case "戌":
            i = "酉未午巳寅午未申酉戌亥子辰";
            break;
        case "亥":
            i = "戌申未午卯巳午未申酉戌亥卯";
            break;
        default:
            i = "";
    }
    o.push({ name: "紫薇", id: n });
    for (var j = 0; j < 13; j++) {
        o.push({ name: Object.keys(STAR_DESCRIPTIONS)[j], id: i[j] });
    }
    return o;
}


// analysisFunctions.js
function calculateLove(starList) {
    var loveStars = starList.filter(star => star.name === "太阴" || star.name === "天同" || star.name === "廉贞");
    var loveAnalysis = "";
    if (loveStars.length > 0) {
        loveAnalysis = "感情运势较为复杂。";
        loveStars.forEach(star => {
            loveAnalysis += `${STAR_DESCRIPTIONS[star.name]}影响下，${getLoveStarEffect(star.name)}`;
        });
    } else {
        loveAnalysis = "感情运势暂不明朗，可多留意自身感受和人际关系变化。";
    }
    return loveAnalysis;
}

function getLoveStarEffect(starName) {
    var effects = {
        "太阴": "感情细腻，可能较为敏感。",
        "天同": "渴望和谐的感情关系，但可能过于随和。",
        "廉贞": "感情忠诚，但情绪波动可能影响感情稳定。",
    };
    return effects[starName] || "";
}

function calculateCareer(starList) {
    var careerStars = starList.filter(star => star.name === "紫微" || star.name === "天府" || star.name === "武曲");
    var careerAnalysis = "";
    if (careerStars.length > 0) {
        careerAnalysis = "事业运势有一定潜力。";
        careerStars.forEach(star => {
            careerAnalysis += `${STAR_DESCRIPTIONS[star.name]}影响下，${getCareerStarEffect(star.name)}`;
        });
    } else {
        careerAnalysis = "事业运势暂不明朗，可积极探索自身优势和发展机会。";
    }
    return careerAnalysis;
}

function getCareerStarEffect(starName) {
    var effects = {
        "紫微": "有领导才能，可能在事业上有较高的成就。",
        "天府": "稳重保守，善于管理，适合在稳定的环境中发展事业。",
        "武曲": "坚毅果断，有财运，可能在金融或商业领域有较好的发展。",
    };
    return effects[starName] || "";
}

function calculateHealth(starList) {
    var healthStars = starList.filter(star => star.name === "天梁" || star.name === "太阴" || star.name === "巨门");
    var healthAnalysis = "";
    if (healthStars.length > 0) {
        healthAnalysis = "健康运势需要注意。";
        healthStars.forEach(star => {
            healthAnalysis += `${STAR_DESCRIPTIONS[star.name]}影响下，${getHealthStarEffect(star.name)}`;
        });
    } else {
        healthAnalysis = "健康运势目前较为平稳，但仍需保持良好的生活习惯。";
    }
    return healthAnalysis;
}

function getHealthStarEffect(starName) {
    var effects = {
        "天梁": "可能有过度劳累的倾向，需要注意休息。",
        "太阴": "情绪可能影响身体健康，需要保持心情舒畅。",
        "巨门": "可能有口腔或消化系统的问题，需要注意饮食健康。",
    };
    return effects[starName] || "";
}

function calculateWealth(starList) {
    var wealthStars = starList.filter(star => star.name === "武曲" || star.name === "贪狼" || star.name === "天府");
    var wealthAnalysis = "";
    if (wealthStars.length > 0) {
        wealthAnalysis = "财运运势有一定波动。";
        wealthStars.forEach(star => {
            wealthAnalysis += `${STAR_DESCRIPTIONS[star.name]}影响下，${getWealthStarEffect(star.name)}`;
        });
    } else {
        wealthAnalysis = "财运运势暂不明朗，可合理规划理财和投资。";
    }
    return wealthAnalysis;
}

function getWealthStarEffect(starName) {
    var effects = {
        "武曲": "有财运，但可能过于刚直，需要注意理财方式。",
        "贪狼": "欲望较强，可能有投资风险，需要谨慎决策。",
        "天府": "善于理财和管理，可能有稳定的财运收入。",
    };
    return effects[starName] || "";
}


function ZiWeiDouShuCalculator() {}

ZiWeiDouShuCalculator.prototype.generateZiWeiData = function (birthday, sex, hour) {
    var lunarData = gregorianToLunar(birthday);

    var g = getDiZhiByMonthAndDay(lunarData, hour);

    var e = [
        { diZhi: "寅", css: { left: 0, bottom: 0 } },
        { diZhi: "卯", css: { left: 0, top: "2 * 240rpx" } },
        { diZhi: "辰", css: { left: 0, top: "1 * 240rpx" } },
        { diZhi: "巳", css: { left: 0, top: 0 } },
        { diZhi: "午", css: { left: "1 * 260rpx", top: 0 } },
        { diZhi: "未", css: { left: "2 * 260rpx", top: 0 } },
        { diZhi: "申", css: { right: 0, top: 0 } },
        { diZhi: "酉", css: { top: "1 * 240rpx", right: 0 } },
        { diZhi: "戌", css: { top: "2 * 240rpx", right: 0 } },
        { diZhi: "亥", css: { right: 0, bottom: 0 } },
        { diZhi: "子", css: { left: "2 * 260rpx", bottom: 0 } },
        { diZhi: "丑", css: { left: "1 * 260rpx", bottom: 0 } },
    ];

    var d = {};
    var y = {};
    for (var i = 0; i < e.length; i++) {
        d[e[i].diZhi] = i;
        y[i] = e[i].diZhi;
    }

    // 生成十二宫信息
    var v = generateTwelvePalaces(d[g], ["命宫", "兄弟宫", "夫妻宫", "子女宫", "财帛宫", "疾厄宫", "迁移宫", "交友宫", "事业宫", "田宅宫", "福德宫", "父母宫"], false);

    var f = determineFiveElementsBureau(lunarData);

    var S = determineZiWeiPalace(lunarData.yinli_num.day, f);

    var z = generateFourteenStars(S);

    // 生成紫微斗数命盘
    var mingPan = {};
    for (var i = 0; i < PALACES.length; i++) {
        mingPan[PALACES[i]] = {
            stars: z.filter(star => star.id === y[i]),
            palaceInfo: PALACES[i],
        };
    }

    // 根据时辰生成命盘解读，并添加具体时间信息
    var interpretation = "";
    for (var palace in mingPan) {
        var starsInPalace = mingPan[palace].stars;
        interpretation += `【${palace}】：`;
        if (starsInPalace.length > 0) {
            for (var j = 0; j < starsInPalace.length; j++) {
                interpretation += `${starsInPalace[j].name}(${STAR_DESCRIPTIONS[starsInPalace[j].name]}), `;
            }
            // 根据时辰添加更详细的描述和具体时间信息
            if (hour >= 0 && hour < 2) {
                interpretation += `子时（23:00 - 01:00），此宫位在宁静的夜晚中蕴含着深沉的思考力量。主星的影响在此刻可能更加内敛，引导你深入反思自身的目标和方向。同时，要注意情绪的稳定，避免过度忧虑影响决策。`;
            } else if (hour >= 2 && hour < 4) {
                interpretation += `丑时（01:00 - 03:00），大地沉睡，此宫位却在黑暗中默默积蓄能量。稳定的主星在此刻可能带来更加坚实的基础，有助于你规划未来的行动。但切勿过于保守，要敢于迈出新的步伐。`;
            } else if (hour >= 4 && hour < 6) {
                interpretation += `寅时（03:00 - 05:00），黎明将至，新的希望开始孕育。此宫位在这个时候充满活力，可能带来新的机遇和挑战。勇敢地迎接变化，但也要谨慎行动，避免冲动带来的不良后果。`;
            } else if (hour >= 6 && hour < 8) {
                interpretation += `卯时（05:00 - 07:00），阳光初现，带来清新与活力。此宫位在这个时刻可能迎来新的开始，积极的能量涌动。然而，要保持冷静，不要被一时的热情冲昏头脑。`;
            } else if (hour >= 8 && hour < 10) {
                interpretation += `辰时（07:00 - 09:00），万物苏醒，稳定的力量主导。此宫位在这个时候运势较为平稳，适合进行长期的规划和发展。但要注意灵活应变，不要过于固执己见。`;
            } else if (hour >= 10 && hour < 12) {
                interpretation += `巳时（09:00 - 11:00），阳光渐强，热情洋溢。此宫位在这个时刻充满活力，积极的行动可能带来进展。但要控制好情绪，避免冲动决策。`;
            } else if (hour >= 12 && hour < 14) {
                interpretation += `午时（11:00 - 13:00），阳光炽热，充满挑战。此宫位在这个时候可能面临一些压力，但也有机会展现自己的能力。保持自信，勇敢面对。`;
            } else if (hour >= 14 && hour < 16) {
                interpretation += `未时（13:00 - 15:00），午后的温和带来和谐。此宫位在这个时候有利于人际关系的发展，与他人的合作可能带来好处。但不要过于依赖他人，保持独立思考。`;
            } else if (hour >= 16 && hour < 18) {
                interpretation += `申时（15:00 - 17:00），活跃的能量涌动。此宫位在这个时候可能迎来新的机会和挑战，善于抓住机遇，同时注意风险。`;
            } else if (hour >= 18 && hour < 20) {
                interpretation += `酉时（17:00 - 19:00），精致与细腻的时刻。此宫位在这个时候可能更加注重细节和品质，追求完美。但不要过于挑剔，保持开放的心态。`;
            } else if (hour >= 20 && hour < 22) {
                interpretation += `戌时（19:00 - 21:00），忠诚与稳定的力量显现。此宫位在这个时候更加可靠，为你提供坚实的支持。但要保持灵活性，不要过于固执。`;
            } else if (hour >= 22 && hour < 24) {
                interpretation += `亥时（21:00 - 23:00），深沉的思考再次回归。此宫位在这个时候内敛而富有智慧，引导你反思一天的经历。保持积极的心态，为新的一天做好准备。`;
            }
        } else {
            interpretation += "暂无主星，但仍有诸多发展可能。";
        }
        interpretation += "\n";
    }

    return {
        mingGong: g,
        shiErGong: v,
        wuXingJu: f,
        ziWeiGongWei: S,
        shiSiZhuXing: z,
        loveAnalysis: calculateLove(z),
        careerAnalysis: calculateCareer(z),
        healthAnalysis: calculateHealth(z),
        wealthAnalysis: calculateWealth(z),
        mingPan: mingPan,
        interpretation: interpretation,
    };
};


export default ZiWeiDouShuCalculator;